import axios from 'axios';
import { message } from "antd";
const { ipcRenderer } = window.require('electron')

/**
 * 封装axios的请求拦截和响应拦截
 *  
 */
function getToken(){
  var token = localStorage.getItem("token");
  if(!token){
    token=sessionStorage.getItem("token");
  }
  return token;
}

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  ipcRenderer.send("log",JSON.stringify(config))

  var token=getToken();
  
  if(token){
    config.headers['LOGIN-TOKEN'] = token;
  }
  
  return config;
}, function (error) {
  return Promise.reject(error);
});



// 添加响应拦截器

axios.interceptors.response.use(function (response) {
  //让返回的结果为response.data的值
  return response.data;
}, function (error) {
  if ((error && error.response)) {
    if (error.response.status === 500 || error.response.status === 501 ||
      error.response.status === 502 | error.response.status === 503 ||
      error.response.status === 504 || error.response.status === 505) {
      window.location.href = "#/server";
    } else if (error.response.status === 401) {
      
      if(error.response.headers["UNAUTHENTICATE"]||error.response.headers["unauthenticate"]){
        localStorage.removeItem("token");
        sessionStorage.removeItem("token");
        window.location.href="#/login"
      }else{
        message.error("你无权访问本页面！！")
        if(!getToken()){
          window.location.href="#/login"
        }
      }
    }else if(error.response.status === 404){
      message.error("访问的地址找不到页面")
    }

  }


  return Promise.reject(error)

});
export default axios;
// export default withRoute(axios);